package com.it.web;

import com.it.service.AiPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 支付记录表（仅用户保费支付场景，强关联保单号） 前端控制器
 * </p>
 *
 * @author yzy
 * @since 2025年09月22日
 */
@RestController
@RequestMapping("/aiPay")
public class AiPayController {
    private static final String RETURN_URL = "http://localhost:8080/payResult";
    @Autowired
    private AiPayService aiPayService;
    //支付记录查询
    @GetMapping("/getAiPayList")
    public R getAiPayList(@RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
                          @RequestParam(value = "policyId",required = false) String policyId,
                          @RequestParam(value = "paymentStatus",required = false) Integer paymentStatus){
        return aiPayService.getAiPayList(pageNum,pageSize,policyId,paymentStatus);
    }
    /**
     * 发起支付宝支付（跳转沙箱支付页面）
     * 接收paymentId，调用Service生成支付表单并响应到前端
     */
    @GetMapping("/pay")
    public void pay(
            @RequestParam("policyId") String policyId,
            @RequestParam("paymentAmount") String paymentAmount,
            HttpServletResponse response) throws IOException {
        //生成支付记录
        String paymentId = aiPayService.createPayRecord(policyId, paymentAmount);
        if (paymentId == null) {
            return;
        }
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
//        request.setReturnUrl("http://localhost:8080/payment");
        String payForm = aiPayService.generateAlipayForm(paymentId, RETURN_URL);
        if (payForm.startsWith("<html>")) {
            // 若返回HTML（异常信息），直接输出
            response.getWriter().write(payForm);
        } else {
            // 若返回正常支付表单，输出并跳转
            response.getWriter().write(payForm);
        }
        // 关闭流
        response.getWriter().flush();
        response.getWriter().close();
    }


    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        // 调用Service层处理回调逻辑，返回支付宝要求的"success"/"fail"
        return aiPayService.handleAlipayNotify(request);
    }



}
